package screen.component
{
	import com.adobe.serialization.json.JSON;
	import com.greensock.TweenLite;
	import com.greensock.easing.Back;
	
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.system.System;
	import flash.text.TextField;
	import flash.utils.Timer;
	import flash.utils.setInterval;
	import flash.utils.setTimeout;
	
	import helper.Services;
	import helper.ValueObject;
	
	import mx.utils.NameUtil;
	
	import screen.ManulifeScreen;

	public class OtherAirplane extends Airplance
	{
		private const CHRISTMAS_SOUND1:String ="0";
		private const CHRISTMAS_SOUND2:String ="1";
		private const CHRISTMAS_SOUND3:String ="2";
		private const ANSWER:String = "answer";
		private const _DURATION:Number=5;
		private var _other_airplane1:MovieClip;
		private var _other_airplane2:MovieClip;
		private var _other_airplane3:MovieClip;
		private var _balloon_name_arr:Array = [["redBalloonMc"],"redBalloonMc","pinkBalloonMC","greenBalloonMC","blueBalloonMc","redBalloonMc","pinkBalloonMC","greenBalloonMC","blueBalloonMc","blueBalloonMc"]
		private var _bg:MovieClip;
		private var _questionMc:MovieClip;
		private var _current_gift:MovieClip=new MovieClip();
		private var _current_point_gift:Point= new Point();
		private var _balloon_ground:MovieClip = new MovieClip;
		private var _remain_time:Number =0;
		private var _timer:Timer;
		private var _show_alert_end_game_bl:Boolean = false;
		private var _service:Services;
		private var _life:Number=-1;
		private var _demo:Number=-1;
		public static var instance:OtherAirplane;
		public function OtherAirplane()
		{
			if(!instance){
				instance = this;
			}
			init();
		}
		public static function getInstance():OtherAirplane{
			if(!instance){
				instance = new OtherAirplane();
			}
			return instance;
		}
		private function init():void{
			//return;
			_balloon_ground = new MovieClip();
			addChild(_balloon_ground);
			for(var i:Number =0;i<12;i++){
				var  balloon:MovieClip =  ValueObject.C1_RESOURCE.getExportedAsset(_balloon_name_arr[Math.floor(Math.random()*10)]) as MovieClip;
				balloon.y = -200;
				balloon.scaleX = balloon.scaleY = 0.4 + 0.6*Math.random();
				_balloon_ground.addChild(balloon);
				setTimeout(tweenAirplane,Math.random()*7000,balloon)
				setInterval(tweenAirplane,3000+Math.random()*5*1000,balloon);
			}
			for(var j:Number =0;j<2;j++){
				var  cube:MovieClip =  ValueObject.C1_RESOURCE.getExportedAsset("cube" + Math.floor(Math.random()*4)) as MovieClip;
				cube.y = -200;
				cube.name = "cube";
				cube.scaleX = cube.scaleY = 0.4 + 0.6*Math.random();
				_balloon_ground.addChild(cube);
				setTimeout(tweenAirplane,Math.random()*10000,cube)
				setInterval(tweenAirplane,15000+Math.random()*10*1000,cube);
			}
			
			_current_gift = new MovieClip();
			addChild(_current_gift);
			
			_bg = ManulifeScreen.getInstance().background;
			with(_bg){
				_questionMc = questionMc;
				buttonImageInit(_questionMc.continuBtn);
				MovieClip(_questionMc.continuBtn).addEventListener(MouseEvent.CLICK,hideQuestion);
				buttonImageInit(playBtn2);
				playBtn2.y = -400;
				MovieClip(playBtn2).addEventListener(MouseEvent.CLICK,btnHandle);
				buttonImageInit(ruleBtn2);
				MovieClip(ruleBtn2)._y = -400;
				MovieClip(ruleBtn2).addEventListener(MouseEvent.CLICK,btnHandle);
				buttonImageInit(closeBtn2);
				MovieClip(closeBtn2).y = - 400;
				MovieClip(closeBtn2).addEventListener(MouseEvent.CLICK,btnHandle);
				buttonImageInit(backBtn);
				MovieClip(backBtn).y = - 400;
				MovieClip(backBtn).addEventListener(MouseEvent.CLICK,btnHandle);
				buttonImageInit(closeBtn);
				MovieClip(closeBtn).addEventListener(MouseEvent.CLICK,btnHandle);
				buttonImageInit(alertEndGame.closeBtn2);
				MovieClip(alertEndGame.closeBtn2).addEventListener(MouseEvent.CLICK,btnHandle);
				buttonImageInit(alertEndGame.playBtn2);
				MovieClip(alertEndGame.playBtn2).addEventListener(MouseEvent.CLICK,btnHandle);
				alertEndGame.y = -400;
				buttonImageInit(inviteFriendBtn);
				MovieClip(inviteFriendBtn).addEventListener(MouseEvent.CLICK,btnHandle);
				inviteFriendMc.y = -400;
				buttonImageInit(inviteFriendMc.copyBtn);
				MovieClip(inviteFriendMc.copyBtn).addEventListener(MouseEvent.CLICK,btnHandle);
				demoMc.y =-400;
				buttonImageInit(demoMc.continuBtn);
				demoMc.addEventListener(MouseEvent.CLICK,navToURL);
			}
			showBtnPlayAndRule();
			
			buttonImageInit(_bg.playBtn);
			MovieClip(_bg.playBtn).addEventListener(MouseEvent.CLICK,btnHandle);
			for(var k:Number=1;k<3;k++){
				var answer:MovieClip = _questionMc.getChildByName(ANSWER+k) as MovieClip;
				answer.buttonMode = true;
				answer.bgMc.alpha =0;
				answer.iconMc.gotoAndStop(k);
				answer.addEventListener(MouseEvent.ROLL_OVER,anserMouseOver);
				answer.addEventListener(MouseEvent.ROLL_OUT,anserMouseOut);
				answer.addEventListener(MouseEvent.CLICK,answerQuestion);
			
			}
			_questionMc.y = -400;
			
			_balloon_ground.mask = _bg.maskMc;
			
			_timer = new Timer(1000);
			_timer.addEventListener(TimerEvent.TIMER,timerHandle);
			_timer.start();
			_service = Services.getInstance();
			for(var l:Number =0;l<3;l++){
				addSound(l.toString(),1);
				volumeSound(l.toString(),0.5);
				stopSound(l.toString());
			}
			
			
			getInfo();
			getInviteFriend();
		}
		private function start(e:MouseEvent):void{
			_service.start(startCompelete,startError);
		}
		private function startCompelete(e:Event):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,startCompelete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,startError);
			var data:Number = JSON.decode(e.target.data);
			//trace("data:",data);
			if(data == 1){
				_life -=1;
				_remain_time = _demo==1?10:120;
				setLife();
				addEvent();
			}else{
				showInviteFriend();
			}

		}
		private function startError(e:IOErrorEvent):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,startCompelete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,startError);
		}
		private function getInfo():void{
			_service.getinfo(getInfoComplete,getInfoError);
		}
		private function getInfoComplete(e:Event):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,getInfoComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,getInfoError);
			try{
				var data:Object = JSON.decode(e.target.data);
				TextField(_bg.userTf).text = data.users;
				TextField(_bg.winnerTf).text = data.winners;
				TextField(_bg.giftTf).text = data.gifts;
				_life=data.life;
				_demo = parseInt(data.demo);
				setLife();
			}catch(e:*){
				_service.traceLog("decode error");
			}
			//TextField(_bg.lifeTf).text = data.life;
		}
		private function setLife():void{
			for(var i:Number =0;i<3;i++){
				var life1:MovieClip = _bg.getChildByName("life" + i) as MovieClip;
				var life2:MovieClip = _bg.alertEndGame.getChildByName("life" + i) as MovieClip;
				if(i<_life){
					life1.gotoAndStop(2);
					life2.gotoAndStop(2);
				}else{
					life1.gotoAndStop(1);
					life2.gotoAndStop(1);
				}
			}
		}
		private function getInfoError(e:IOErrorEvent):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,getInfoComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,getInfoError);
			_service.traceLog("getInfoError");
		}
		private function shoot():void{
			_service.shoot(shootComplete,shootError);;
		}
		private function shootComplete(e:Event):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,shootComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,shootError);
			var data:Number = JSON.decode(e.target.data);
			switch(data){
				case 0:
					return;
					break;
				case 1://trai tim
					_remain_time +=10;
					MovieClip(_bg.bonus).gotoAndStop(1);
					TextField(_bg.bonus.bonusMc.remainTf).text = "+10s";
					MovieClip(_bg.bonus).play();
					break;
				case 2:// not nhac
					for(var i:Number =1;i<4;i++){
						stopSound(i.toString());
					}
					var music_name:String =Math.min(2,Math.floor(Math.random()*3)).toString();
					resumeSound(music_name);
					break;
				case 3://thiep giang sinh
				case 4:// may anh
				case 5:// ve xem phim
				case 6:// mu bao hiem
				case 7:// dong ho de ban
				case 8:// khung anh
					break;
				case 9:// bom
					_remain_time = Math.max(0,_remain_time - 5);
					MovieClip(_bg.bonus).gotoAndStop(1);
					TextField(_bg.bonus.bonusMc.remainTf).text = "-5s";
					MovieClip(_bg.bonus).play();
					break;
				default:
					return;
					break;
			}
			_current_gift.stop();
			this.removeChild(_current_gift);
			_current_gift = ValueObject.C2_RESOURCE.getExportedAsset("G"+data) as MovieClip;
			_current_gift.x = _current_point_gift.x;
			_current_gift.y = _current_point_gift.y;
			addChild(_current_gift);
		}
		private function shootError(e:IOErrorEvent):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,shootComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,shootError);
		}
		private function getQuestion():void{
			_service.getQuestion(getQuestionComplete,getQuestionError);
		}
		private function getQuestionComplete(e:Event):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,getQuestionComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,getQuestionError);
			var data:Object = JSON.decode(e.target.data);
			TextField(_questionMc.questionTf).text = data.question;
			for(var i:Number=1;i<3;i++){
				var answer:MovieClip = _questionMc.getChildByName("answer"+i) as MovieClip;
				if(data["answer"+i] !=""){
					answer.visible = true;
					answer.answerTf.text = data["answer"+i];
				}else{
					answer.visible = false;
				}
				
			}
			showQuestion()
			removeEvent();
		}
		private function getQuestionError(e:IOErrorEvent):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,getQuestionComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,getQuestionError);
		}
		private function answerQuestion(e:MouseEvent):void{
			var answer:MovieClip = e.currentTarget as MovieClip;
			var answer_choice:String = answer.name.substring(ANSWER.length,ANSWER.length +1);
			_service.answerQuestion(answerQuestionComplete,answerQuestionError,answer_choice);
			
		}
		private function answerQuestionComplete(e:Event):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,answerQuestionComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,answerQuestionError);
			var data:Number = JSON.decode(e.target.data);
			if(data == 1){
				_life = Math.min(3,_life+1);
				TextField(_questionMc.questionTf).htmlText = '<font  size="15">Chúc mừng bạn đã có thêm 1 lượt chơi!</font>';
				setLife();
			}else{
				TextField(_questionMc.questionTf).htmlText = '<font size="15">Hãy chọn đáp án đúng để giành được 1 lượt chơi nữa!</font>';
			}
			for(var i:Number=1;i<3;i++){
				var answer:MovieClip = _questionMc.getChildByName("answer"+i) as MovieClip;
				answer.visible = false;
			}
		}
		private function answerQuestionError(e:IOErrorEvent):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,answerQuestionComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,answerQuestionError);
			hideQuestion()
		}
		private function getInviteFriend():void{
			_service.getInviteFriend(getInviteFriendComplete,getInviteFriendError);
		}
		private function getInviteFriendComplete(e:Event):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,getInviteFriendComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,getInviteFriendError);
			//trace("e.target.data:",e.target.data);
			//var data:String = JSON.decode(e.target.data);
			TextField(_bg.inviteFriendMc.linkTf).text = e.target.data;
		}
		private function getInviteFriendError(e:IOErrorEvent):void{
			URLLoader(e.target).removeEventListener(Event.COMPLETE,getInviteFriendComplete);
			URLLoader(e.target).removeEventListener(IOErrorEvent.IO_ERROR,getInviteFriendError);
		}
		private function btnHandle(e:MouseEvent):void{
			var btn:MovieClip = e.currentTarget as MovieClip;
			switch(btn.name){
				case "playBtn":
				case "playBtn2":
					if(Popup.getInsctance().onShow){
						Popup.getInsctance().hide();
						return;
					}
					start(e);
					hideBtnPlayAndRule();
					hideBtnCloseAndBack();
					break;
				case "ruleBtn2":
					Popup.getInsctance().tabBtnHandle(e);
					hideBtnPlayAndRule()
					break;
				case "closeBtn":
					hideBtnPlayAndRule()
					showBtnCloseAndBack();
					break;
				case "closeBtn2":
					navigateToURL(new URLRequest("http://diemtuatinhthan.com/game"),"_parent");
					hideBtnCloseAndBack()
					break;
				case "backBtn":
					hideBtnCloseAndBack()
					break;
				case "inviteFriendBtn":
					if(Popup.getInsctance().onShow){
						Popup.getInsctance().hide();
					}
					hideAll();
					showInviteFriend();
					break;
				case "copyBtn":
					hideAll();
					System.setClipboard(TextField(_bg.inviteFriendMc.linkTf).text);
					break;
			}
		}
		private function showBtnCloseAndBack():void{
			removeEvent();
			TweenLite.to(_bg.closeBtn2,0.5, { y:23,ease:Back.easeOut} );
			TweenLite.to(_bg.backBtn,0.5, { y:23,ease:Back.easeOut} );
		}
		public function hideBtnCloseAndBack():void{
			hideAll();
			setTimeout(addEvent,500);
		}
		private function showBtnPlayAndRule():void{
			TweenLite.to(_bg.playBtn2,0.5, { y:23,ease:Back.easeOut} );
			TweenLite.to(_bg.ruleBtn2,0.5, { y:23,ease:Back.easeOut} );
		}
		public function hideBtnPlayAndRule():void{
			hideAll();
		}
		private function showQuestion():void{
			TweenLite.to( _questionMc,0.5, { y:23,ease:Back.easeOut} );
		}
		private function hideQuestion(e:MouseEvent=null):void{
			hideAll();
			setTimeout(addEvent,500);
		}
		private function showInviteFriend():void{
			TweenLite.to( _bg.inviteFriendMc,0.5, { y:23,ease:Back.easeOut} );
		}
		private function showDemo():void{
			if(!_show_alert_end_game_bl){
				return;
			}
			TweenLite.to( _bg.demoMc,0.5, { y:23,ease:Back.easeOut} );
		}
		private function hideAll():void{
			TweenLite.to(_bg.closeBtn2,0.5, { y:-400} );
			TweenLite.to(_bg.backBtn,0.5, { y:-400} );
			TweenLite.to(_bg.playBtn2,0.5, { y:-400} );
			TweenLite.to(_bg.ruleBtn2,0.5, { y:-400} );
			TweenLite.to(_bg.alertEndGame,0.5, { y:-400} );
			TweenLite.to(_bg.inviteFriendMc,0.5, { y:-400} );
			TweenLite.to(_questionMc,0.5, { y:-400} );
		}
		public function checkShoot(disp:MovieClip):Boolean{
			var leng:Number = _balloon_ground.numChildren;
			for (var i:Number = 0;i<leng ;i++){
				var balloon:MovieClip = _balloon_ground.getChildAt(i) as MovieClip;
				if(balloon.hitTestObject(disp)){
					balloon.gotoAndPlay("fired");
					if(balloon.name =="cube"){
						getQuestion();
						return true;;
					}
					_current_point_gift.x = balloon.x;
					_current_point_gift.y = balloon.y-30;
					shoot();
					return true;
				}
			}
			return false;
			//Tank.getInstance().shootCamiAirPlane(this);
		}
		private function airplaneClick(e:MouseEvent):void{
			//Tank.getInstance().shootOtherAirplane(this);
		}
		private function tweenAirplane(mc:MovieClip):void{
			if(mc.y > -150 || _remain_time == 0){
				return;
			}
			var current_fly:Number=0;
			var leng:Number = _balloon_ground.numChildren;
			for(var i:Number = 0;i<leng;i++){
				var balloon:MovieClip = _balloon_ground.getChildAt(i) as MovieClip;
				if(balloon.y >20){
					current_fly++;
				}
			}
			if(current_fly >=3){
				return;
			}
			mc.gotoAndPlay("normal");
			mc.y = 400;
			mc.x= 350 + 400*Math.random();
			var duration:Number = _demo == 1? _DURATION+10:_DURATION + 0.1*_remain_time;
			TweenLite.to(mc,duration,{y:-250});
		}
		private function removeEvent():void{
			_timer.stop();
			ManulifeScreen.getInstance().removeEventListener(MouseEvent.CLICK,Tank.getInstance().shootAirPlane);
			ManulifeScreen.getInstance().removeEventListener(MouseEvent.MOUSE_MOVE,Tank.getInstance().mouseMoveHandle);
		}
		private function addEvent():void{
			_timer.start();
			ManulifeScreen.getInstance().addEventListener(MouseEvent.CLICK,Tank.getInstance().shootAirPlane);
			ManulifeScreen.getInstance().addEventListener(MouseEvent.MOUSE_MOVE,Tank.getInstance().mouseMoveHandle);
		}
		private function anserMouseOver(e:MouseEvent):void{
			MovieClip(e.target.bgMc).alpha = 0.5;
		}
		private function anserMouseOut(e:MouseEvent):void{
			MovieClip(e.target.bgMc).alpha = 0;
		}
		private function timerHandle(e:TimerEvent):void{
			if(_remain_time >0){
				_show_alert_end_game_bl = true;
				_remain_time -=1;
				var hh:Number =Math.floor(_remain_time/3600);
				var mm:Number = Math.floor((_remain_time - hh*3600)/60);
				var ss:Number = _remain_time - hh*3600 - mm*60;
				TextField(_bg.remainTf).text = formatNumber(mm)+"'"+formatNumber(ss)+"''";
			}else {
				removeEvent();
				if(_demo == 1){
					showDemo();
				}else {
					showAlertEndGame();
				}
				
			}
		}
		private function showAlertEndGame():void{
			if(!_show_alert_end_game_bl){
				return;
			}
			TweenLite.to(_bg.alertEndGame,0.5, { y:23,ease:Back.easeOut} );
			TextField(_bg.alertEndGame.contentTf).text = "Bạn đã mất một lượt chơi, bạn có muốn chơi tiếp không";
			
		}
		private function navToURL(e:MouseEvent):void{
			navigateToURL(new URLRequest("http://diemtuatinhthan.com/game"));
		}
		private function formatNumber(no:Number):String{
			if(no<10){
				return "0"+no.toString();
			}else{
				return no.toString();
			}
		}
	}
}